package org.gary.base.dao.impl;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.dbcp.BasicDataSource;
import org.gary.base.dao.XxxImageDao;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

/**
 * 
 * @author lengreen
 *
 */
@Component("xxxImageDao")
public class XxxImageDaoImpl implements XxxImageDao {
	private String sql;
	private BasicDataSource dataSource;
	private HibernateTemplate hibernateTemplate;

	public void deleteByImageId(String target, int imageId) {
		setSql("delete from " + target + "_image where images_id=" + imageId);
		new JdbcTemplate(dataSource).execute(new StatementCallback<Object>() {

			@Override
			public Object doInStatement(Statement stmt) throws SQLException,
					DataAccessException {
				stmt.executeUpdate(sql);
				return null;
			}
		});
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List deleteByXxxId(String target, int xxxId) {
		setSql("select images_id from " + target + "_image where " + target + "_id = " + xxxId);
		List imagesIds = hibernateTemplate.execute(new HibernateCallback<List>() {

			@Override
			public List doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q = session.createSQLQuery(getSql());
				return q.list();
			}
		});
		setSql("delete from " + target + "_image where " + target + "_id in (" + xxxId + ")");
		new JdbcTemplate(dataSource).execute(new StatementCallback<Object>() {

			@Override
			public Object doInStatement(Statement stmt) throws SQLException,
					DataAccessException {
				stmt.executeUpdate(sql);
				return null;
			}
		});
		return imagesIds;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public String getSql() {
		return sql;
	}

	@Resource
	public void setDataSource(BasicDataSource dataSource) {
		this.dataSource = dataSource;
	}

	public BasicDataSource getDataSource() {
		return dataSource;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

}
